package com.jms;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;

import javax.jms.*;

/**
 * Created by simon on 16-6-13.
 */
public class test3 {
    public static void main(String[] args) throws Exception {
//        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost");
//        Connection connection = factory.createConnection();
//        connection.start();
//
//        Queue queue = new ActiveMQQueue("testQueue");
//        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
//
//        MessageProducer producer = session.createProducer(queue);
//        producer.setDeliveryMode(DeliveryMode.PERSISTENT);//消息持久化
//        producer.send(session.createTextMessage("A persistent Message"));
//
//        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);//消息不持久化
//        producer.send(session.createTextMessage("A non persistent Message"));
//
//        System.out.println("Send messages sucessfully!");//   }

        //先执行以上代码。在执行下面代码打印：Consumer get A persistent Message， 说明消息持久化了。

        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost");
        Connection connection = factory.createConnection();
        connection.start();

        Queue queue = new ActiveMQQueue("testQueue");
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        MessageConsumer comsumer = session.createConsumer(queue);
        comsumer.setMessageListener(new MessageListener() {
            public void onMessage(Message m) {
                try {
                    System.out.println("Consumer get " + ((TextMessage) m).getText());
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        });
        //另外, 如果发送一个non persistent消息, 而刚好这个时候没有消费者在监听, 这个消息也会丢失.
    }
}
